package com.web.hilover.service.impl;

import com.web.hilover.entity.User;
import com.web.hilover.mapper.UserMapper;
import com.web.hilover.service.UserService;
import com.web.hilover.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public User register(String username, String password) {
        User existUser = userMapper.findByUsername(username);
        if (existUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        String salt = MD5Util.generateSalt();
        String encryptPassword = MD5Util.encrypt(password, salt);
        
        User user = User.builder()
                .username(username)
                .password(encryptPassword)
                .salt(salt)
                .role(0)
                .nickname(username)
                .gender(0)
                .build();
                
        userMapper.insert(user);
        return user;
    }
    
    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        
        String encryptPassword = MD5Util.encrypt(password, user.getSalt());
        if (!user.getPassword().equals(encryptPassword)) {
            throw new RuntimeException("密码错误");
        }
        
        return user;
    }
    
    @Override
    public void updatePassword(Long id, String password) {
        User user = userMapper.findById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        String encryptPassword = MD5Util.encrypt(password, user.getSalt());
        int rows = userMapper.update(User.builder()
                .id(id)
                .password(encryptPassword)
                .build());
                
        if (rows != 1) {
            throw new RuntimeException("密码更新失败");
        }
    }
    
    @Override
    public User getUserById(Long id) {
        return userMapper.findById(id);
    }
    
    @Override
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }
    
    @Override
    public boolean updateUser(User user) {
        log.info("Updating user: {}", user);
        try {
            int rows = userMapper.update(user);
            return rows == 1;
        } catch (Exception e) {
            log.error("Failed to update user: {}", e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean deleteUser(Long id) {
        return userMapper.deleteById(id) > 0;
    }
} 